import { hotSearchApi } from '@/api/search'
import { searchStore } from '@/store/modules/search'
import { defineComponent, reactive } from 'vue'
import { useRouter } from 'vue-router'
import SearchRecord from './SearchRecord'
import SearchInput from '@/components/SearchInput'
import { useSearchEffect } from '@/hooks/useSearch'

interface HotSearchData {
  list: string[]
}

/* 搜索功能 */
const useHotSearchEffect = () => {
  const { search, searchText } = useSearchEffect()
  const data = reactive({
    list: []
  }) as HotSearchData
  const getHotSearch = async () => {
    const res = await hotSearchApi()
    if (res.code === 0) {
      data.list = res.data
    }
  }
  getHotSearch()

  return {
    search,
    searchText,
    data
  }
}

export default defineComponent({
  name: 'Search',
  setup () {
    const router = useRouter()
    const { search, searchText, data } = useHotSearchEffect()
    /* render 函数 */
    return () => {
      return (
        <div class="search">
          <header>
            <SearchInput
              v-model={ searchText.value }
              onKeyup={ search }
              placeholder="请输入商家名称搜索" />
            <div class="cancel" onClick={ () => { router.back() } }>取消</div>
          </header>
          <SearchRecord title="搜索历史" showClear records={ searchStore.records } onSearch={ search } />
          <SearchRecord title="热门搜索" records={ data.list } onSearch={ search } />
        </div>
      )
    }
  }
})
